package com.sike.netty.im.client.handler;

import com.sike.netty.im.client.event.JoinGroupEvent;
import com.sike.netty.im.client.service.BeanFactory;
import com.sike.netty.im.client.service.ClientService;
import com.sike.netty.im.common.command.JoinGroupRequestCommand;
import com.sike.netty.im.common.command.Message;
import com.sike.netty.im.common.command.MessageBuilder;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.Scanner;

/**
 * 加入群聊请求 handler
 *
 * @author chenssy
 * @date 2023/09/20
 */
public class JoinGroupRequestHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof JoinGroupEvent) {
            ClientService clientService = (ClientService) BeanFactory.getServiceBean(ClientService.class);
            // 加入群聊菜单
            joinGroupMenu();

            new Thread(() -> {
                Scanner scanner = new Scanner(System.in);
                String[] lines;
                while (true) {
                    lines = scanner.nextLine().split(" ");
                    switch (lines[0]) {
                        case "01":
                            doJoinGroup(ctx,lines);
                            break;
                        case "02":
                            clientService.toMainMenu(ctx);
                            return;
                        case "00":
                            clientService.exitLogin(ctx);
                            return;
                    }
                }
            }).start();
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }

    /**
     * 加入群聊
     *
     * @param ctx
     * @param lines
     */
    private void doJoinGroup(ChannelHandlerContext ctx, String[] lines) {
        JoinGroupRequestCommand joinGroupRequestCommand = new JoinGroupRequestCommand(lines[1]);
        Message message = MessageBuilder.buildMessage(joinGroupRequestCommand,null,null);
        ctx.channel().writeAndFlush(message);
    }

    /**
     * 加入群聊菜单
     */
    private void joinGroupMenu() {
        System.out.println("|-------------------------------------|");
        System.out.println("|            加入群聊界面               |");
        System.out.println("|加入群聊：01 groupId                   |");
        System.out.println("|02:返回主菜单                          |");
        System.out.println("|00:退出登录                            |");
        System.out.println("|------------------------------------- |");
    }
}
